<?php
// ----------------------------------------------------------------------
// pn-commerce Shopping Cart Solution for PostNuke
// http://pncommerce.de
// http://www.sourceforge.net/projects/pn-commerce/
//
// It is based on PostKart 0.701QA from
//			Destin LeBlanc [ postkart@zenflesh.com ]
// ----------------------------------------------------------------------
// Source file:  $Source: /cvsroot/pn-commerce/pn-commerce/pnsmgenericapi.php,v $
//
// Last changes from:  $Author: landseer $
//
// Revision:           $Revision: 1.31 $
//
// Date of revision    $Date: 2004/09/12 15:12:42 $
//  
// ----------------------------------------------------------------------
// LICENSE
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License (GPL)
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// To read the license please visit http://www.gnu.org/copyleft/gpl.html
// ----------------------------------------------------------------------

require_once("modules/pncommerce/common.php");

/**
 * load the config array and return it
 * no arguments needed
 */
function pncommerce_smgenericapi_getConfig ($args=array())
{
  $data=pnModGetVar ('pncommerce', 'smgenericData');
  if(isset($data)) return unserialize($data);
  else return false;
}

/**
 * save the config array
 * @param $args array of config values
 */
function pncommerce_smgenericapi_setConfig ($args)
{
    pnModSetVar ( 'pncommerce', 'smgenericData',serialize($args));
}



/**
 * You ask the user for some input here, or redirect him to the next stage.
 * *******
 * You have to redirect to 'checkout' when you are ready!
 * *******
 */
function pncommerce_smgenericapi_getdata($args)
{
	// no need to ask for anything, just forward
	pnRedirect( pnModURL( 'pncommerce', 'user', 'checkout' ) );
	return true;
}

/**
 * This function is not always necessary, it's just here for templating purposes
 * You can do something with the data entered in getData here
 * *******
 * You have to redirect to 'checkout' when you are ready!
 * *******
 */
function pncommerce_smgenericapi_getdataresponse($args)
{
}


/**
 * This function get's called after the user has agreed to buy the items in his cart.
 * You can calculate show informations here or ask for data to finish the shippingprocess
 * *******
 * You have to redirect to 'receipt' when you are ready!
 * *******
 */
function pncommerce_smgenericapi_processshipping ($args)
{
	pnRedirect( pnModURL( 'pncommerce', 'user', 'receipt' ) );
	return true;
}

/**
 * Asks the user if the order (remove,activate, deactivate) should be processed
 * @param $args['Mode']  'install','remove','activate','deactivate'
 * @return String 
 * @returns A Errorpage or the "Are you sure"  page
 */
function pncommerce_smgenericapi_configintro()
{
	$Mode = pnVarCleanFromInput ('Mode');
	if (!pnModAPILoad('pncommerce', 'user'))
      {
        return showerrorpage("unable to load pnuserapi", __FILE__, __LINE__);
      }
	if (pnSecAuthAction(0, '::', '::', ACCESS_ADMIN))
	{
	    switch( $Mode )
		{
		case 'install':
            //This is a generic ShippingMethod, we can simulate many simple Shipping Companies
            //that doesn't need any special data
            //For this we have a array of arrays with the data for each company.
		    $default=array(""._PNC_DEFAULTCOMPANY => array('PMCalcFunc'=>'PMCFlat',
			                'PMCFlatPrice' =>0,
			                'name' => _PNC_DEFAULTCOMPANY,
			                'Description' => _PNC_DEFAULTCOMPANYDESC));
		    pncommerce_smgenericapi_setConfig($default);
		    pnModSetVar ('pncommerce', 'smgeneric', 'on');
	        break;
	    case 'remove':
    		pncommerce_smgenericapi_quietremove();
	        break;
	    case 'activate':
    		pnModSetVar ('pncommerce', 'smgeneric', 'on');
	        break;
	    case 'deactivate':
		    pnModSetVar ('pncommerce', 'smgeneric', 'off');
	        break;
	    default:
		}
       	pnRedirect( pnModAPIFunc('pncommerce','user','pncModURL',
								array('Module'=>'pncommerce', 'Section'=> 'admin', 'Function'=>'shippingmethodconfig')));
        return true;
    }
	else
	{
		return showerrorpage( _PNC_NOAUTH, __FILE__, __LINE__ );
	}
}

/**
 * Shows the code for the radio-buttoned list of all available shipping methods
 * @returns String
 */
function pncommerce_smgenericapi_showoption($args)
{
	extract ($args);
	$config=pncommerce_smgenericapi_getConfig();
	foreach($config as $company){
		$temp .="<input type='radio' name='ShippingMethod' value='smgeneric_".$company['name']."'";
		if ( $BSM == 'smgeneric_'.$company['name'] )
		{
			$temp .= " checked ";
		}
		$temp .= ">".$company['Description']."<br>\n";
	}
	return $temp;
}

/**
 * calculates the  number of options simulated of this method.
 * @returns Array
 * @return 'isSingle' bool true if there is only one option active
 * @return 'ShippingMethod' the name of the simulated option useable for the hidden field
  */
function pncommerce_smgenericapi_isSingleOption($args)
{
	extract ($args);
	$config=pncommerce_smgenericapi_getConfig();
	$count=0;
	foreach($config as $company){
		$BSM = 'smgeneric_'.$company['name'];
		$count++;
		$name=$company['name'];
	}
	return array('isSingle'=>($count==1),'ShippingMethod'=>$BSM,'name'=>$name);
} 

/*
 * returns the footermessage of the chosen SM
 *@param $args['ShippingMethod'] the shippingmethod in this form 'smgeneric_<SCompanyName>'
 *@returns string
 * @return string when SCompany could be found, otherwise _PNC_NOTDEFINED
 */
function pncommerce_smgenericapi_footermsg ($args)
{
	$config=pncommerce_smgenericapi_getConfig();
	foreach($config as $company){
		//test which one we should use
		if($args['ShippingMethod']=='smgeneric_'.$company['name']){
			return $company['Footermsg'];
		}
	}
	return _PNC_NOTDEFINED;
}


/**
 * returns the descriptive name of the shippingmethod
 * @param $args['method'] string 2nd part of complete name, e.g. post from smgeneric_post or ups from smgeneric_ups
 * @returns string
 */
function pncommerce_smgenericapi_info($args)
{
    extract( $args );
	$config=pncommerce_smgenericapi_getConfig();
//	$method = "$_method";
	foreach($config as $company)
	{
	    if( strtolower($company['name']) == strtolower($method) )
        {
            return $company['Description'];
        }
	}
	return (_PNC_GENERICSHIPPINGMETHOD);
}

/**
 * removes all config-data of the shippingmethod in the DB and it's status using
 * pnModDelVar ('pncommerce', 'smgeneric');	
 */
function pncommerce_smgenericapi_quietremove ()
{
	pnModDelVar ('pncommerce', 'smgeneric');	
	pnModDelVar ('pncommerce', 'smgenericData');	
	return true;
}

/**
 * Asks for special data for this shipping method, for example minimum fee or default fee, ...
 * ****
 * You have to redirect to 'shippingmethodconfig' when you're done
 * ****
 * @return String 
 * @returns the config page for this Shiping method
 */ 
function pncommerce_smgenericapi_config()
{
    if (!pnModAPILoad('pncommerce', 'user'))
    {
        return showerrorpage("unable to load pnuserapi", __FILE__, __LINE__);
    }
    if (!pnModAPILoad('pncommerce', 'admin'))
    {
        return showerrorpage("unable to load pnadminapi", __FILE__, __LINE__);
    }

    if (pnSecAuthAction(0, '::', '::', ACCESS_ADMIN))
    {
        $Submit = pnVarCleanFromInput( 'Submit' );
        
        $smarty = new pnRender();
        $smarty->caching = false;
        $config = pncommerce_smgenericapi_getConfig();
            
        if( !$Submit )
        {
            // we need to add a temporary payment _new here so that pncommerce_admin_pmcalclist
            // can set the fieldname in the form correctly
            // the trick is set we ad the 'new' at the end of the array. When howing all the 
            // existing generic methods this be skipped and used for the potential new payment
            // at the end
            // we only need the name
            $config['new']['name'] = 'new';
            $smarty->assign( 'smgenericconfig', $config );
            return $smarty->fetch( 'pncommerce_smgeneric_configuration.html' );
        }                              
        else  // submit is set
        {
    
            if( !pnSecConfirmAuthKey() ) 
            { 
                return showerrorpage( _PNC_BADAUTHKEY, __FILE__, __LINE__ ); 
            }     
    
	    	$storage=array();
	    	// first step: extract the keys from the config array to see which generics we 
	    	// have there
            // and here we also need the "new" item again
            $config['new']['name'] = "new";
	    	$generics = array_keys( $config );
            // cycvle through the keys
	    	foreach($generics as $oldname)
	    	{
                //check if we have to delete it
	    		if(!((pnVarCleanFromInput('remove_'.$oldname)=='true')
	    				||(pnVarCleanFromInput('name_'.$oldname)=='')))
	    		{
	    			$act=array();
                    //we use this here to gather informations, for this we need the old name
	    			$act['name'] = $oldname;
	    			$act['Description'] = pnVarCleanFromInput('Description_'.$oldname );
	    			$act['Footermsg'] = pnVarCleanFromInput('Footermsg_'.$oldname);
	    			$act['PMCalcFunc'] = pnVarCleanFromInput('PMCalcFunc'.$oldname);
	    			$act=pnModAPIFunc('pncommerce','user','gatherPMCalcData',$act);
                    //now we can use the real name
                    $name = pnVarCleanFromInput('name_'.$oldname);
	    			$act['name'] = str_replace( "_", "", str_replace(" ", "", $name ) );
	    			$storage[$act['name']]=$act;
        
	    		}
	    	}
	    	pncommerce_smgenericapi_setConfig($storage);
	    	pnRedirect( pnModAPIFunc('pncommerce','user','pncModURL',
	    								array('Module'=>'pncommerce', 'Section'=> 'admin', 'Function'=>'shippingmethodconfig')));
	    	return true; 
        }
    }
    return false;
}

/**
 * Calculates the shipping fee based on all prior given data
 * @param $args['KID']  'install','remove','activate','deactivate'
 * @param $args['WeightTotal']  double total weight of the order
 * @param $args['ItemsTotal']  double total amount of items in the order
 * @param $args['Subtotal']  double total amount of the itemcosts
 * @param $args['ShippingMethod']  string, e.g. smgeneric_Post, we need this to get the information which company-info we need to load
 * @return Double 
 * @returns the resulting fee 
 */
function pncommerce_smgenericapi_getShippingTotal($args)
{
//echo"<pre>";print_r($args);echo"</pre>";
//die();
//Return 0 = this Paymethod is for free
	if (!pnModAPILoad('pncommerce', 'user'))
    {
        return showerrorpage("unable to load pnuserapi", __FILE__, __LINE__);
    }
	$config=pncommerce_smgenericapi_getConfig();
	foreach($config as $company)
	{
		//test which one we should use
		if($args['ShippingMethod']=='smgeneric_'.$company['name'])
		{
			//add value to array to make the function able to calculate the fee
			$company['Value']=$args['SubTotal'];
			return pnModAPIFunc('pncommerce','user','getPMCalcValue',$company);
		}
	}
	//When we get here that we got an error

	return -9999;//delete this after debugging
}

/*
 * getGenericShippingmethodNames
 * return an array of all the installed generic shippingmethods
 *
 *@returns array containing 'name' and 'Description'
 */
function pncommerce_smgenericapi_getGenericShippingmethodNames()
{
	$config=pncommerce_smgenericapi_getConfig();
    $generics = array();
	foreach($config as $company)
	{
	    $generic = array();
        $generic['name'] = $company['name'];
        $generic['Description'] = $company['Description'];
        array_push( $generics, $generic );
	}
    return $generics;
}

?>
